package com.sskj.api.aspect;

import com.sskj.api.domain.SysUser;
import com.sskj.api.domain.UserLoginLog;
import com.sskj.api.exception.LogicException;
import com.sskj.api.service.ISysUserService;
import com.sskj.api.service.IUserLoginLogService;
import com.sskj.api.vo.req.AdminLoginReq;
import com.sskj.common.dto.IPRegionInfo;
import com.sskj.common.util.IPUtil;
import com.sskj.common.util.StrUtil;
import com.sskj.common.util.UserAgentUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import nl.basjes.parse.useragent.UserAgent;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class LoginLogAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private IUserLoginLogService userLoginLogService;

    @Pointcut("@annotation(com.sskj.api.annotation.LoginLog)")
    public void logPointCut(){}

    @Autowired
    private ISysUserService adminUserService;

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable  {
        Object[] args = point.getArgs();
        AdminLoginReq adminLoginReq = (AdminLoginReq)args[0];
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setLoginType(adminLoginReq.getType());

        SysUser sysUser = adminUserService.getByPhone(adminLoginReq.getPhone());
        if (sysUser != null) {
            userLoginLog.setUserId(sysUser.getId());
        }

        String ip = IPUtil.getIpAddress(httpServletRequest);
        if (StrUtil.isNotBlank(ip)) {
            userLoginLog.setLoginIp(ip);

            IPRegionInfo regionInfo = IPUtil.getRegionByIP(ip);
            if (regionInfo != null) {
                userLoginLog.setLoginRegion(regionInfo.getProvince() + regionInfo.getCity());
            }
        }
        String userAgentStr = httpServletRequest.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        userLoginLog.setOperatingSystemName(userAgent.getValue("OperatingSystemNameVersionMajor"));
        userLoginLog.setAgentName(userAgent.getValue("AgentNameVersionMajor"));
        userLoginLog.setCreateTime(LocalDateTime.now());

        try {
            Object proceed = point.proceed();
            userLoginLog.setLoginStatus(1);
            userLoginLog.setRemarks("登录成功");

            return proceed;
        } catch (LogicException e) {
            userLoginLog.setLoginStatus(0);
            userLoginLog.setRemarks(e.getMessage());
            throw e;
        } finally {
            userLoginLogService.save(userLoginLog);
        }
    }
}
